<template>
  <div>
    <Uploader @fileclick="fileclick" :type="type" :files="value" :data-type="dataType" :limit="limit" :uploadList="uploadList" ref="uploader" :dragdrop="dragdrop" :class-name="className" @deletefile="deletefile">
      <div slot="dragdrop" v-if="$slots.dragdrop"><slot name="dragdrop"></slot></div>
    </Uploader>
  </div>
</template>
<script>

import Pluploadjs from 'plupload-es6';
import utils from 'hey-utils';

export default {
  props: {
    options: {
      type: Object,
      default: () => { }
    },
    type: {
      type: String,
      default: 'image'
    },
    dataType: String,
    dragdrop: {
      type: Boolean,
      default: false
    },
    value: {
      type: [Object, Array, String]
    },
    limit: Number,
    className: String
  },
  data() {
    return {
      uploadList: [],
    };
  },
  methods: {
    deletefile(index) {
      let value = null;
      if (this.type == 'images' || this.type == 'files') {
        value = utils.copy(this.value);
        value.splice(index, 1);
      } else {
        value = null;
        this.uploadList = [];
      }
      this.$emit('input', value);
    },
    init() {
      let that = this;
      let url = '/api/file/upload';
      let dragdropElement = true;
      let params = {};
      let filters = this.options;
      let param = {
	    runtimes: 'html5',
	    browse_button: this.$refs.uploader.getBrowseButton(),
	    url: `${url}`,
	    domain: '',
	    chunk_size: '1mb',
      headers: {
          'token': Utils.getLocal('token')
      },
	    unique_names: true,
	    multi_selection: this.limit > 1,
	    filters,
	    init: {
	      FilesAdded(up, files) {
	      	console.log(files,up,'FilesAdded');
	        if (that.limit && (files.length + that.value.length > that.limit)) {
              that.$Message.error(`你上传的文件超过${that.limit}个。`);
              return;
            }
            files.forEach((file) => {
              if (FileReader) {
                let reader = new FileReader();
                reader.onload = (event) => {
                  file.thumbUrl = event.target.result;
                };
                reader.readAsDataURL(file.getNative());
              }
              if (that.type == 'files' || that.type == 'images') {
                that.uploadList.push(file);
              } else {
                that.uploadList = [file];
              }
            });
            up.start();
	        // getUploadToken().then(() => { // 获取上传token，如果没有可以直接跳过，直接调用up.start();
	        //   up.start();
	        // });
	      },
	      BeforeUpload(up, file) {
	        
	      },
	      UploadProgress(up, file) {
            // log(file.percent);
          },
          FileUploaded(up, file, info) {           
            let res = JSON.parse(info.response);
            let sourceLink = `${res.file_path}`; // 获取上传成功后的文件的Url
            log('FileUploaded', that.dataType,res);
            file.url = sourceLink;
            file.name = sourceLink;
          },
          Error(up, err, errTip) {
            that.uploadList.splice(0, that.uploadList.length);
            that.$Message.error(errTip);
          },
          UploadComplete() {
            that.$emit('completeUpload');
            let fileList = that.$refs.uploader.getFileList();
            //   fileList.map(item=>{
            //     // 对返回的数据做最后的组装
            //     // item.type = 5;
            //     // item.fileType = ...
            //   })
            log('completeUpload',fileList);
            that.$emit('input', fileList);
            if (that.type == 'files' || that.type == 'images') {
              that.uploadList.splice(0, that.uploadList.length);
            }
          }
	    },
	  };

	  // 是否允许拖拽
	  if (this.dragdrop) {
	    param.dragdrop = true;
	    param.drop_element = this.$refs.uploader.getDropElement();
	  }
	  Utils.extend(param, params);
	  const uploader = new Pluploadjs.plupload.Uploader(param);
	  uploader.init();
    },
    fileclick(file) {
      this.$Modal({
        title: '预览或者下载',
        content: `自定义处理文件预览或者下载`
      });
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  }
};
</script>
